package com.imooc.security.browser.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.imooc.security.core.properties.LoginType;
import com.imooc.security.core.properties.SecurityProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by zghgchao 2018/4/21 11:32
 */
@Component("imoocAuthenticationSuccessHandler")//别名
//public class ImoocAuthenticationSuccessHandler implements AuthenticationSuccessHandler{
//Spring 默认的登录成功处理器 SavedRequestAwareAuthenticationSuccessHandler
public class ImoocAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler{

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ObjectMapper objectMapper;//SpringMVC在启动时会自动为我们注册一个ObjectMapper

    @Autowired
    private SecurityProperties securityProperties;

    /**
     * 登录成功后会调用
     * @param request
     * @param response
     * @param authentication  封装认证信息
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        logger.info("登录成功");

        if (LoginType.JSON.equals(securityProperties.getBrowser().getLoginType())){
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(authentication));
        }else {//如果不是JSON，使用父类方法实现跳转
            super.onAuthenticationSuccess(request,response,authentication);
        }


    }
    /**
     * 返回的authentication数据
     * {
     "  authorities": [
             {
                "authority": "admin"
             }
         ],
         "details": {
             "remoteAddress": "0:0:0:0:0:0:0:1",
             "sessionId": null
         },
         "authenticated": true,
         "principal": {  //UserDetail
             "password": null,     //密码
             "username": "tom",   //用户名
             "authorities": [
                 {
                     "authority": "admin"
                 }
             ],
             "accountNonExpired": true,
             "accountNonLocked": true,
             "credentialsNonExpired": true,
             "enabled": true
         },
         "credentials": null,   //密码已做处理
         "name": "tom"          //登录用户名
         }
     *
     */
}
